 /*
 * Managed bean used for logging into the application
 * 
 */
package controllers;

import helpers.Utils;
import java.io.Serializable;
import java.sql.*;
import javax.enterprise.context.SessionScoped;
import javax.faces.context.FacesContext;
import javax.inject.Named;
import models.Admin;
import models.User;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;

/**
 * 
 * @author luci
 */
@Named(value = "loginBean")
@SessionScoped
public class Login implements Serializable {    
    
    private transient static Logger logger = LogManager.getLogger(Login.class.getName());
    
    private String password;
    private String email;
    private Integer userID;
    private boolean invalidUser = false;
    private boolean logedIn = false;
    private String name;    
    
    static final String FAIL="fail";
    static final String SUCCESS="success";
    
    /**
     * Creates a new instance of LoginBean
     */
    
    
    public Login() {
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public boolean isLogedIn() {
        return logedIn;
    }

    public void setLogedIn(boolean logedIn) {
        this.logedIn = logedIn;
    }
    
    

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }
    
    public Integer getUserID() {
        return userID;
    }

    public void setUser_id(Integer userID) {
        this.userID = userID;
    }

    public boolean isInvalidUser() {
        return invalidUser;
    }
    
     public String logout() {
        setLogedIn(false);
        FacesContext.getCurrentInstance().getExternalContext().invalidateSession();
        return SUCCESS;
     }
    public String checkValidUser(){
        logger.info("User Login atttempt with email "
              +email+" and password "
              +password);
        return checkCredentials(User.TABLE_NAME);
    }  
    
    public String loginAdminAction(){
        logger.info("Admin Login atttempt with email "
                +email+" and password "
                +password);
        return checkCredentials(Admin.TABLE_NAME);
       
    }
    
    private String checkCredentials(String tableName){
        if (this.password == null || 
                this.password.equals("") ||
                this.email == null ||
                this.email.equals("")) {
            return FAIL;
        }
        Connection sqlConnection = null;
        try{           
            sqlConnection = Utils.getConnection();
            StringBuilder query = new StringBuilder("SELECT id, name, last_name FROM ");
            query.append(tableName);
            query.append(" WHERE ");
            query.append(User.EMAIL_FIELD_NAME);
            query.append("=? AND ");
            query.append(User.PASSWORD_FIELD_NAME);
            query.append("=?");
            PreparedStatement ps = 
                sqlConnection.prepareStatement(query.toString());
            ps.setString(1, email);
            ps.setString(2, password);
            ResultSet rs = ps.executeQuery();            
            
            if (!rs.next()) {                
                invalidUser = true;                
            }else{
                invalidUser = false;
                setLogedIn(true);
                userID = rs.getInt("id");
                //clear user password, don't need to store in the loginBean
                setPassword("");
            }           
            rs.close();            
        }catch(SQLException ex){
            logger.error("Login failed. Exception occoured",ex);
            ex.printStackTrace(System.out);           
        }finally{//code always executed
             try{
                if (sqlConnection!=null && !sqlConnection.isClosed()){
                    sqlConnection.close();
                }
            }catch(SQLException ex){
               logger.error("Error closing connection ", ex);                
            }
            if (isLogedIn()){
               logger.info("Login SUCCESSFUL");
                
                return SUCCESS;                
            }else {
                logger.info("Login FAILED");
                return FAIL;
            } 
        }    
    }
}
